<?php

namespace App\Http\Controllers\API;

use App\Events\PusherEvent;
use App\Events\TestEvent;
use App\Models\City;
use App\Models\StartUpLogo;
use App\Services\CurlService;
use App\Services\Socket;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Lzq\Mqtt\SamConnection;
use Lzq\Mqtt\SamMessage;
use App\Services\Logger;
use App\Services\Store;

class CommonAPIController extends Controller
{
    /**
     * @api {get} api/city/:type/:pid 获取城市数据
     * @apiVersion 1.0.0
     * @apiName getCity
     * @apiGroup Common
     *
     * @apiParam {String} type 类型(0:国,1:省,2:市,3:区)
     * @apiParam {String} pid 父节点,type为0的时候是0,查找中国各省即100000
     *
     * @apiHeader {String} Accept=application/json
     * @apiHeader {String} Authorization Bearer xxxxx
     *
     * @apiSuccess {Number} id 主键
     * @apiSuccess {String} name 省市区名称
     * @apiSuccess {String} parentid 上级ID
     * @apiSuccess {String} shortname 简称
     * @apiSuccess {String} leveltype 级别:0,中国；1，省分；2，市；3，区、县
     * @apiSuccess {String} citycode 城市代码
     * @apiSuccess {String} zipcode 邮编
     * @apiSuccess {Number} lng 经度
     * @apiSuccess {Number} lat 纬度
     * @apiSuccess {String} pinyin 拼音
     *
     * @apiSuccessExample {json} 返回城市信息数组
     *     HTTP/1.1 200 OK
     * 略
     *
     */
    public function getCity($type, $pid)
    {
        $condition = [
            'parentid' => $pid,
            'leveltype' => $type,
            'status' => '1'
        ];
        $city = City::where($condition)->get()->toArray();
        return $this->success($city);
    }

    /**
     * @api {get} startup/logos  启动页面获取
     * @apiVersion 1.0.0
     * @apiName getStartupLogo
     * @apiGroup Common
     *
     * @apiSuccess (200) {String} id
     * @apiSuccess (200) {String} image
     * @apiSuccess (200) {String} enable'是否启用 1 启用 2 禁用'
     * @apiSuccess (200) {String} url'访问 URL'
     * @apiSuccess (200) {String} type'类型(1: 图片 2: gif 3: 其他)'
     * @apiSuccess (200) {String} remark'备注'
     */
    public function getStartupLogo()
    {
        $logos = StartUpLogo::where('enable', 1)->get();
        //event(new PusherEvent('测试'));
        return $this->success($logos);
    }

    public function mqttSend()
    {
        $conn = new SamConnection();
        $res = $conn->connect('mqtt', array('SAM_HOST' => '123.207.28.142', 'SAM_PORT' => '1883'));//start initialise the connection
        $msgCpu = new SamMessage('hehe');//create a new MQTT message with the output of the shell command as the body

        $res = $conn->send('topic://' . 'topicTest02', $msgCpu);//send the message on the topic cpu
        $conn->disconnect();
    }

    public function mqttSubscribe()
    {
        $conn = new SamConnection();
        $res = $conn->connect('mqtt', array('SAM_HOST' => '123.207.28.142', 'SAM_PORT' => '1883'));//start initialise the connection

        $res = $conn->subscribe('topic://' . 'topicTest03');//send the message on the topic cpu
        dd($res);
        $conn->disconnect();
        $host = '123.207.28.142';
        $port = 1883;

        $r = new \mqttclient\src\swoole\MqttClient($host, $port, 10017);
        $r->setAuth('username', 'password');
        $r->setKeepAlive(60);
        $r->setLogger(new Logger());
        $r->setStore(new Store());
        $r->setTopics(
            [
                new \mqttclient\src\subscribe\Topic('test/slim', function ($msg) {
                    echo "I receive:" . $msg . "\r\n";
                }),
                new \mqttclient\src\subscribe\Topic('test/slim3', function (\mqttclient\src\swoole\MqttClient $client, $msg) {
                    echo "I receive:" . $msg . " for slim3 \r\n";
                    echo $client->getClientId();
                })
            ]
        );

//set trigger
        $r->on(\mqttclient\src\consts\ClientTriggers::RECEIVE_SUBACK, function (\mqttclient\src\swoole\MqttClient $client) {
            $client->publish('slim/echo', 'GGXX', \mqttclient\src\consts\Qos::ONE_TIME);
        });

        $r->connect();
        $r->publish('test/slim', 'test qos', 2);
    }

    public function mqttReceive()
    {
        $conn = new SamConnection();
        $res = $conn->connect('mqtt', array('SAM_HOST' => '123.207.28.142', 'SAM_PORT' => '1883'));//start initialise the connection

        $res = $conn->receive('59faba5643f5a7.52729814#-#topicTest03',['SAM_WAIT'=>0]);//send the message on the topic cpu
//        dd($res);
//        $conn->disconnect();
    }

    public function curl(Request $request)
    {
        $input = $request->all();
        $res = CurlService::curl($input['url'], $input['params'], 1, 0);
        $json = json_decode($res);
        dd($res);
    }

    public function socket(Request $request)
    {
        $input = $request->all();
        $socket = new Socket($input['url'], 80, SOL_TCP);
        $res = $socket->connect();
        $res = $socket->sendMessage($input['params']);

//        $res = $socket->sendMessageTo($input['params'],'192.168.1.110',80);
        dd($res);
    }
}
